<template>
  <div>
    <div id="graphContainer"></div>
  </div>
</template>

<script>
// import mxgraph from "./mxgraph";
import mxgraph from "./graph/index"; 
const {
  mxGraph,
  mxClient,
  mxCodec,
  mxUtils,
  mxConstants,
  mxPerimeter,
  mxHierarchicalLayout,
  mxCompactTreeLayout,
} = mxgraph;

export default {
  data() {
    return {
      v_graph: "",
      v_parent: "",
      mxgraphData: [
        {
          nodesList: [
            [0, "宝鸡市"],
            [1, "渭南市"],
            [2, "西安市"],
            [3, "汉中市"],
            [4, "安康市"],
          ],
          edgesList: [
            [0, "200Km", 1],
            [1, "300km", 2],
            [1, "75Km", 3],
            [3, "100Km", 4],
            [4, "90Km", 5],
          ],
        },
      ],
    };
  },

  methods: {
    /**
     * 生成节点
     */
    createNodes(graph, parent) {
      //遍历mxgraphData生成节点

      var len = this.mxgraphData[0].nodesList.length;

      for (var i = 0; i < len; i++) {
        let text = this.mxgraphData[0].nodesList[i][1];
        let id = `node${this.mxgraphData[0].nodesList[i][0]}`;
        var node = graph.insertVertex(
          parent,
          id,
          text,
          0,
          0,
          150,
          40,
          "fillColor=#3CAEA3;strokeColor=white;fontStyle=1;fontColor=white;rounded=1;fontSize=15;"
        );
      }
    },

    /**
     * 生成边
     */
    createEdges(graph, parent) {
      var len = this.mxgraphData[0].edgesList.length;
      for (var i = 0; i < len; i++) {
        //寻找到对应的节点id
        var startIndex = `node${this.mxgraphData[0].edgesList[i][0]}`;
        var endIndex = `node${this.mxgraphData[0].edgesList[i][2]}`;
        
        //graph.getModel().getCell()  通过id找到对应的节点node
        var v1 = graph.getModel().getCell(startIndex);
        var v2 = graph.getModel().getCell(endIndex);
        
        var label = this.mxgraphData[0].edgesList[i][1];
        var eage = graph.insertEdge(parent, null, label, v1, v2, "");
      }
    },
  },

  mounted() {
    if (!mxClient.isBrowserSupported()) {
      // 判断是否支持mxgraph
      mxUtils.error("Browser is not supported!", 200, false);
    } else {
      // 在容器中创建图表
      let container = document.getElementById("graphContainer");

      var graph = new mxGraph(container);
      var parent = graph.getDefaultParent();
      this.v_graph = graph;
      this.v_parent = parent;

      // 生成 Hello world!

      graph.getModel().beginUpdate();

      //定义布局
      var layout = new mxHierarchicalLayout(graph);

      try {
        this.createNodes(graph, parent);
        this.createEdges(graph, parent);
        layout.execute(parent);
      } finally {
        // Updates the display
        graph.getModel().endUpdate();
      }
    }
  },
};
</script>

<style>
#graphContainer {
  width: 1000px;
  height: 700px;
  border: 3px solid rgb(194, 185, 185);
  /* background-image: url("../assets/grid.gif"); */
  margin: auto;
  box-sizing: border-box;
  padding: 100px 0 0 250px;
}
</style>